package weixinOperator

import (
	"bytes"
	"encoding/json"
	"fmt"
	"github.com/astaxie/beego/orm"
	"github.com/tidwall/gjson"
	"io/ioutil"
	"net/http"
	"strings"
	"t11Lib/t11Errors"
	"t11Lib/t11Http"
	"t11Lib/t11Log"
	"t11Lib/t11Model"
	"亚太-iot-服务器/conf"
	"亚太-iot-服务器/models"
)

//加载微信用户详细信息
func doGetWxUserInfo(appId, openId string) (*models.WxUser, t11Errors.T11Error) {
	ak, err := MpManager.GetAccessToken(appId)
	if err != nil {
		return nil, err
	}
	reqUrl := fmt.Sprintf("https://api.weixin.qq.com/cgi-bin/user/info?access_token=%s&openid=%s&lang=zh_CN", ak, openId)
	body, err := t11Http.Get(reqUrl)
	if err != nil {
		return nil, err
	}
	info := &models.WxUser{}
	t11Log.Debug("body = ", string(body))
	oerr := json.Unmarshal(body, info)
	t11Log.Debug("获取用户详细信息完成， info = ", info, ", err = ", oerr)
	return info, t11Errors.Wrap(oerr, "获取微信用户详细信息失败")
}
func GetWxUserInfo(conn *t11Model.DbConn, appId, openId string) (*models.WxUser, t11Errors.T11Error) {
	t11Log.Debuglnf("获取微信用户信息")
	u, e := models.WxUserDao.GetByOpenId(conn, appId, openId)
	if e == nil {
		return u, e
	}
	if e.GetInner() != orm.ErrNoRows {
		return nil, e
	}
	//添加微信用户信息
	u, e = doGetWxUserInfo(appId, openId)
	if e != nil {
		return nil, e
	}
	//将微信用户注册到数据库中
	u.SetId(appId, openId)
	return u, models.WxUserDao.SaveWxUser(conn, u)
}

//获取微信用户的openId
func GetWxUserByCode(appId, code string) (*models.WxUser, t11Errors.T11Error) {
	appSecret := conf.WxCfgManager.GetAppSecret(appId)
	if appSecret == "" {
		return nil, t11Errors.New("非法的appId")
	}
	requestLine := strings.Join([]string{"https://api.weixin.qq.com/sns/oauth2/access_token",
		"?appid=", appId,
		"&secret=", appSecret,
		"&code=", code,
		"&grant_type=authorization_code"}, "")
	t11Log.Debuglnf("requestUrl = %v", requestLine)
	resp, err := http.Get(requestLine)
	if err != nil || resp.StatusCode != http.StatusOK {
		return nil, t11Errors.Wrap(err, "发送get请求获取 openid 错误")
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, t11Errors.Wrap(err, "发送get请求获取 openid 读取返回body错误")
	}
	t11Log.Debug("body = ", string(body))
	if bytes.Contains(body, []byte("errcode")) {
		return nil, t11Errors.Wrap(err, "发送get请求获取 openid 的错误信息:\n")
	} else {
		obj := gjson.ParseBytes(body)
		openId := obj.Get("openid").Str

		if openId == "" {
			return nil, t11Errors.Wrap(err, "发送get请求获取 openid 返回数据json解析错误")
		}
		return GetWxUserInfo(t11Model.NewDbConn(), appId, openId)
	}
}
